package com.yiwei.zxp.activity;

import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.yiwei.zxp.R;
import com.yiwei.zxp.api.Api;
import com.yiwei.zxp.api.bean.BankAddBean;
import com.yiwei.zxp.api.bean.BankBinBean;
import com.yiwei.zxp.api.bean.RegisterSendCodeBean;
import com.yiwei.zxp.base.BaseActivity;
import com.yiwei.zxp.event.BankTypeEvent;
import com.yiwei.zxp.util.Network;
import com.yiwei.zxp.util.RxLifeUtil;
import com.yiwei.zxp.util.ToastUtil;
import com.yiwei.zxp.util.UI;
import com.yiwei.zxp.util.Util;
import com.yiwei.zxp.view.V19FrameLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import butterknife.Unbinder;

/**
 * Created by xsooy-pc on 17-12-8.
 */

public class BankCardAddActivity extends BaseActivity {
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.btn_card_type)
    TextView btnCardType;
    @BindView(R.id.btn_send_code)
    TextView btnSendCode;
    @BindView(R.id.btn_submit)
    TextView btnSubmit;
    @BindView(R.id.edit_bankcard)
    EditText editBankcard;
    @BindView(R.id.edit_realname)
    EditText editRealname;
    @BindView(R.id.edit_mobile)
    EditText editMobile;
    @BindView(R.id.edit_code)
    EditText editCode;
    @BindView(R.id.edit_idcard)
    EditText editIdcard;

    private Unbinder unbiner;
    private String bankType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bankcard_add);
        initWebViewBar();
        unbiner = ButterKnife.bind(this);
        init();
        EventBus.getDefault().register(this);
    }

    private void init() {
        txtTitle.setText("添加银行卡");
        editBankcard.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s == null || s.length() == 0) return;
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < s.length(); i++) {
                    if (i != 4 && i != 9 && i != 14 && i != 19 && s.charAt(i) == ' ') {
                        continue;
                    } else {
                        sb.append(s.charAt(i));
                        if ((sb.length() == 5 || sb.length() == 10 || sb.length() == 15 || sb.length() == 20) && sb.charAt(sb.length() - 1) != ' ') {
                            sb.insert(sb.length() - 1, ' ');
                        }
                    }
                }
                if (!sb.toString().equals(s.toString())) {
                    int index = start + 1;
                    if (sb.charAt(start) == ' ') {
                        if (before == 0) {
                            index++;
                        } else {
                            index--;
                        }
                    } else {
                        if (before == 1) {
                            index--;
                        }
                    }
                    editBankcard.setText(sb.toString());
                    editBankcard.setSelection(index);
                }

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (UI.toString(editBankcard).length() >= 6 && UI.toString(editBankcard).length() <= 9) {
                    getBankBin(UI.toString(editBankcard));
                }
            }
        });
//        Util.setBankChange(editBankcard);
    }


    @OnTextChanged({R.id.edit_realname, R.id.edit_mobile, R.id.edit_code})
    void afterTextChanged(Editable s) {
        if (!TextUtils.isEmpty(UI.toString(editBankcard)) &&
                !TextUtils.isEmpty(UI.toString(editRealname)) &&
                !TextUtils.isEmpty(UI.toString(editMobile)) &&
                !TextUtils.isEmpty(UI.toString(editCode))) {
            btnSubmit.setBackgroundResource(R.drawable.btn_check_gredient);
        }
    }

    private static final int TIME = 60 * 1000;  //验证码倒计时时间
    private CountDownTimer timer = new CountDownTimer(TIME, 1000) {

        @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
        @Override
        public void onTick(long millisUntilFinished) {
            btnSendCode.setEnabled(false);
            btnSendCode.setText((millisUntilFinished / 1000) + "s");
            btnSendCode.setTextColor(0xFFCCCCCC);
        }

        @Override
        public void onFinish() {
            resetBtn();
        }
    };


    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void resetBtn() {
        if (timer != null) timer.cancel();
        btnSendCode.setEnabled(true);

        btnSendCode.setText("获取验证码");
        btnSendCode.setTextColor(0xFFFF0030);
    }

    public void getBankBin(String bankcard_no) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        BankBinBean bean = new BankBinBean();
        bean.bankbin = bankcard_no;
        Api.api_service.getBankBin(bean).compose(RxLifeUtil.NocheckOn(this)).
                doFinally(() -> {
                    try {

                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    if (result.code.equals("00")) {
                        btnCardType.setText((result.datas.bank_name == null ? "" : result.datas.bank_name) + (result.datas.bank_type == null ? "" : result.datas.bank_type));
                    }
                });
    }

    public void getSmsSend(String mobile) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        RegisterSendCodeBean bean = new RegisterSendCodeBean();
        bean.mobile = mobile;
        Api.api_service.getSendCode(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    timer.start();
                    ToastUtil.makeText(this, "发送成功");
                });
    }

    public void getBankAdd(String bank_id, String bankcard, String mobile, String realname, String smscode, String idno) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        BankAddBean bean = new BankAddBean();
//        bean.bank_id = bank_id;
        bean.bankcard = bankcard;
        bean.mobile = mobile;
        bean.realname = realname;
        bean.smscode = smscode;
        bean.idno = idno;
        Api.api_service.getBankAdd(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    ToastUtil.makeText(this, "添加成功");
                    finish();
                });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(BankTypeEvent event) {
        btnCardType.setText(event.bankName);
        bankType = event.bankId;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            resetBtn();
        }
        EventBus.getDefault().unregister(this);
        unbiner.unbind();
        unbiner = null;
    }

    @OnClick({R.id.btn_back, R.id.btn_card_type, R.id.btn_send_code, R.id.btn_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_card_type:
                Util.startActivity(this, BankSelectActivity.class);
                break;
            case R.id.btn_back:
                finish();
                break;
            case R.id.btn_send_code:
                if (TextUtils.isEmpty(UI.toString(editMobile))) {
                    ToastUtil.makeText(this, "手机号不能为空");
                    return;
                }
                getSmsSend(UI.toString(editMobile));
                break;
            case R.id.btn_submit:
                if (TextUtils.isEmpty(UI.toString(editBankcard))) {
                    ToastUtil.makeText(this, "银行卡号不能为空");
                    return;
                }
                if (TextUtils.isEmpty(UI.toString(editRealname))) {
                    ToastUtil.makeText(this, "持卡人姓名");
                    return;
                }
//                if (TextUtils.isEmpty(bankType)) {
//                    ToastUtil.makeText(this, "开户行不能为空");
//                    return;
//                }
                if (TextUtils.isEmpty(UI.toString(editMobile))) {
                    ToastUtil.makeText(this, "手机号不能为空");
                    return;
                }
                if (TextUtils.isEmpty(UI.toString(editCode))) {
                    ToastUtil.makeText(this, "短信验证码不能为空");
                    return;
                }
                if (TextUtils.isEmpty(UI.toString(editIdcard))) {
                    ToastUtil.makeText(this, "身份证不能为空");
                    return;
                }
                getBankAdd(bankType, UI.toString(editBankcard), UI.toString(editMobile), UI.toString(editRealname), UI.toString(editCode), UI.toString(editIdcard));
                break;
        }
    }
}
